package main

import (
	"fmt"
	"go-demo/code_database"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

/*
	TodoItem 代办事项
*/
type Status int8

const (
	TaskHasDone  = 1
	TaskNeedTodo = 0
)

type TodoItem struct {
	Id        uint      `json:"id"`
	Name      string    `json:"name" gorm:"NOT NULL"`
	Status    bool      `json:"status"`
	DoneAt    time.Time `json:"done_at" gorm:"default:null"`
	CreatedAt time.Time `json:"created_at"`
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}
func main() {
	router := gin.Default()
	router.Use(Cors())
	db, err := code_database.ConnectInit()
	db.AutoMigrate(&TodoItem{})
	if err != nil {
		fmt.Printf("数据库链接失败%v", err)
	} else {
		fmt.Println("数据库连接成功")
	}

	router.LoadHTMLGlob("web/*")
	router.GET("/index.html", func(context *gin.Context) {
		context.HTML(http.StatusOK, "index.html", nil)
	})
	router.POST("/todo", func(context *gin.Context) {
		name := context.PostForm("name")
		todoItem := &TodoItem{Name: name, Status: false, CreatedAt: time.Now()}
		if err := db.Create(&todoItem).Error; err != nil {
			context.JSON(http.StatusBadRequest, gin.H{
				"message": "创建失败",
			})
		} else {
			context.JSON(http.StatusOK, gin.H{
				"message": "创建成功",
			})
		}
	})
	router.GET("/todo", func(context *gin.Context) {
		todoList := make([]TodoItem, 100)
		err := db.Find(&todoList).Error
		if err != nil {
			context.JSON(http.StatusOK, gin.H{
				"message": fmt.Sprintf("查询代办异常%v", err),
			})
		} else {
			context.JSON(http.StatusOK, gin.H{
				"data": todoList,
			})
		}
	})
	router.PUT("/todo/:id", func(context *gin.Context) {
		// 根据id查询，然后修改
		todoId := context.Param("id")
		var todoItem TodoItem
		db.Where("id=?", todoId).Find(&todoItem)
		todoItem.Status = true
		todoItem.DoneAt = time.Now()
		save := db.Save(todoItem)
		context.JSON(http.StatusOK, gin.H{
			"data": save,
		})
	})
	router.DELETE("/todo/hasDone", func(context *gin.Context) {
		var hasDoneItems []TodoItem
		db.Where("status=?", true).Find(&hasDoneItems)
		for _, item := range hasDoneItems {
			db.Delete(item)
		}
		context.JSON(http.StatusOK, gin.H{
			"message": hasDoneItems,
		})
	})
	router.Run(":8989")
}
